package com.wenhai.spring.event;

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.context.event.EventListenerMethodProcessor;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * {@link ApplicationListener} 示例
 *
 * @author wenhai
 * @date   2021/4/19
 * @see ApplicationListener
 * @see EventListener
 * @see EventListenerMethodProcessor
 */
@EnableAsync(proxyTargetClass = true)
public class ApplicationListenerDemo implements ApplicationEventPublisherAware, BeanPostProcessor {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(ApplicationListenerDemo.class);
        // 方法一：基于接口
        // 具体 ContextRefreshedEvent 事件
        // context.addApplicationListener((ApplicationListener<ContextRefreshedEvent>) event -> System.out.println("接收到 Spring 事件：" + event));
        // 类 ApplicationEvent 监听器
        context.addApplicationListener(event -> System.out.println("ddApplicationListener 接收到 Spring 事件：" + event));
        context.refresh();
        context.start();
        context.close();
    }

    @EventListener
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("@EventListener 接收到 Spring 事件：" + event);
    }

    @EventListener
    @Async
    @Order(1)
    public void onApplicationAsyncEvent(ApplicationEvent event) {
        System.out.println("order[1] onApplicationAsyncEvent 接收到 Spring 事件：" + event + "， 线程id " + Thread.currentThread().getName());
    }
    @EventListener
    @Async
    @Order(2)
    public void onApplicationAsyncEvent2(ApplicationEvent event) {
        System.out.println("order[2]onApplicationAsyncEvent 接收到 Spring 事件：" + event + "， 线程id " + Thread.currentThread().getName());

    }


    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        applicationEventPublisher.publishEvent("hello");

    }
}
